About 2726 letters

About 14 minutes

#Python's Iterators and Iterable Objects

#Iterator

An iterator in Python is a tool used to traverse collection objects. It provides a unified way to access elements in a collection.

In Python, an object is considered an iterator if it implements the __next__ method. This method returns the next item in the sequence each time it is called, and raises a StopIteration exception when there are no more items.

You can retrieve the next item from an iterator using the built-in next function.

Example:

import io # Iterator class class Iterator: def __init__(self, stop): self.__stop = stop self.__current = 0 # Return items one by one def __next__(self): if self.__current < self.__stop: self.__current += 1 return self.__current - 1 else: raise StopIteration # Create an iterator object iterator = Iterator(10) # Iterate while (value := next(iterator, None)) is not None: print(value)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Iterable Object

An iterable object is an object that contains an iterator. In Python, any object that implements the __iter__ method is considered iterable. This method is responsible for returning an iterator.

You can obtain an iterator from an iterable using the built-in iter function.

Example:

# Iterator class class Iterator: def __init__(self, stop): self.__stop = stop self.__current = 0 # Return items one by one def __next__(self): if self.__current < self.__stop: self.__current += 1 return self.__current - 1 else: raise StopIteration # Iterable class class Iterable: def __init__(self, stop): self.__iterator = Iterator(stop) def __iter__(self): return self.__iterator # Create an iterable object iterable = Iterable(10) # for loop iteration for value in iterable: print(value)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

It's not necessary to implement iterators and iterables as two separate classes. Often, the iterable object is its own iterator by having the __iter__ method return self.

For example:

# Object that is both iterable and an iterator class Iterator: def __init__(self, stop): self.__stop = stop self.__current = 0 def __next__(self): if self.__current < self.__stop: self.__current += 1 return self.__current - 1 else: raise StopIteration # Return self as iterator def __iter__(self): self.__current = 0 # Reset state return self # Create an iterator iterator = Iterator(10) # for loop iteration for value in iterator: print(value)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Created in 5/23/2025

Updated in 5/23/2025